package com.pets.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.pets.ViewModels.StatisticsViewModels;
import com.pets.pojo.FeedbackManagement;
import com.pets.pojo.FinancialManagement;
import com.pets.mapper.FinancialManagementMapper;
import com.pets.service.IFinancialManagementService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.pets.utils.Result;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.temporal.ChronoUnit;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;
import java.util.stream.IntStream;

/**
 * <p>
 * 财务管理 服务实现类
 * </p>
 *
 * @author 小陳同學
 * @since 2024-05-13
 */
@Service
public class FinancialManagementServiceImpl extends ServiceImpl<FinancialManagementMapper, FinancialManagement> implements IFinancialManagementService {

    @Autowired
    private FinancialManagementMapper financialManagementMapper;

    @Override
    public Result register(FinancialManagement financialManagement) {
        if(financialManagement== null){
            return Result.fail("未获取到参数");
        }
        if(financialManagement.getFinancialName() == null){
            return Result.fail("未设置到名称");
        }
        if(financialManagement.getPrice() == null){
            return Result.fail("未设置价格");
        }
        financialManagement.setCreateTime(LocalDateTime.now());
        return financialManagementMapper.insert(financialManagement) > 0 ? Result.success("成功") : Result.fail("失败");
    }

    @Override
    public Result deleteById(Integer id) {
        int rows = financialManagementMapper.deleteById(id);
        return rows > 0 ? Result.success("删除成功") : Result.error("删除失败");
    }

    @Override
    public Result update(FinancialManagement financialManagement) {
        int rows = financialManagementMapper.updateById(financialManagement);
        return rows > 0 ? Result.success("修改成功") : Result.error("修改失败");
    }

    @Override
    public Result selectPage(Integer page, Integer pageSize, String financialName) {
        final LambdaQueryWrapper<FinancialManagement> lqw = new LambdaQueryWrapper<>();
        lqw.like(financialName != null&&!financialName.isEmpty(), FinancialManagement::getFinancialName, financialName)
                .orderByDesc(FinancialManagement::getCreateTime);
        IPage<FinancialManagement> Page = new Page<>(page, pageSize);
        IPage<FinancialManagement> IPage = financialManagementMapper.selectPage(Page, lqw);
        return Result.success("查询成功", IPage);
    }

    @Override
    public Result orderStatistics(LocalDate beginTime, LocalDate endTime) {
        //返回模型
        List<StatisticsViewModels> statisticsViewModelsList = new ArrayList<>();
        if (beginTime==null||endTime==null){
            return Result.fail("开始时间与结束时间不能为空！");
        }
        // 确保开始日期不晚于结束日期
        if (beginTime.isAfter(endTime)) {
            return Result.fail("开始日期不能晚于结束日期！");
        }
        //查询账单集合
        LambdaQueryWrapper<FinancialManagement> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.ge(FinancialManagement::getCreateTime, beginTime.atStartOfDay())
                .lt(FinancialManagement::getCreateTime, endTime .plusDays(1).atStartOfDay());
        List<FinancialManagement> financialManagementList = financialManagementMapper.selectList(queryWrapper);
        if (financialManagementList == null||financialManagementList.size()==0){
            return Result.success("成功",statisticsViewModelsList);
        }
        // 计算两个日期之间的天数差（包括两个日期本身）
        long daysBetween = ChronoUnit.DAYS.between(beginTime, endTime) + 1;
        // 使用IntStream生成包含所有日期的列表
        List<LocalDate> datesBetween = IntStream.rangeClosed(0, (int) (daysBetween - 1))
                .mapToObj(beginTime::plusDays)
                .collect(Collectors.toList());
        for (LocalDate localDate : datesBetween) {
            StatisticsViewModels statisticsViewModels = new StatisticsViewModels();
            statisticsViewModels.setTime(localDate.toString());//时间
            //查询当天下记录
            List<FinancialManagement> collect = financialManagementList.stream()
                    .filter(a -> {
                        LocalDate entityDate = a.getCreateTime().toLocalDate();
                        return entityDate.equals(localDate);
                    }).collect(Collectors.toList());
            BigDecimal sum = BigDecimal.ZERO; // 初始化总和为0
            if (collect.size() > 0){
                statisticsViewModels.setDownloadRecordCount(collect.size());
                for (FinancialManagement financialManagement : collect) {
                    sum = sum.add(financialManagement.getPrice());
                }
                statisticsViewModels.setPriceCount(sum);
            }else {
                statisticsViewModels.setDownloadRecordCount(0);
                statisticsViewModels.setPriceCount(sum);
            }
            statisticsViewModelsList.add(statisticsViewModels);
        }
        return Result.success("成功",statisticsViewModelsList);
    }
}
